package com.sjh.lib_app.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import me.drakeet.multitype.ItemViewBinder
import com.sjh.lib_app.BR

/**
 * 配合multitype使用的适配器，使用方法和 BaseAdapter<T,BD> 一致
 * 使用方式
 * ```kotlin
 * test_rv.apply {
 *  val apt = MultiTypeAdapter().apply {
 *      register<Int,TestitemImgsBinding>(R.layout.testitem_imgs)
 *      register<String, TestItemStringBinding>(R.layout.test_item_string)
 *               .onBind = {itemBinding, data ->
 *                  itemBinding.root.onClick {
 *                  println("点击了item，内容是$data")
 *          }
 *      }
 *  }
 *  apt.items = arrayListOf(R.drawable.test_banner_1,"123",R.drawable.test_banner_2,R.drawable.test_banner_3,R.drawable.test_banner_4,"890",R.drawable.test_banner_5)
 *  layoutManager = LinearLayoutManager(context)
 *  adapter = apt
 * }
 * ```
 * @author Extends
 * @date 2018/7/15/015
 */
class BaseBinder<T, BD : ViewDataBinding>(@LayoutRes private val layoutId: Int) : ItemViewBinder<T, BaseBinder.Companion.Holder>() {
    var onBind: ((itemBinding: BD, data: T, position: Int) -> Unit)? = null
    override fun onBindViewHolder(holder: Holder, item: T) {
        val position = getPosition(holder)
        (holder.getBinding() as BD).apply {
            setVariable(BR.item, item)
            setVariable(BR.position,position)
        }
//        if_onBind?.onBind(viewHolder.getBinding() as T2,realPosition,data)
        //不加这一行，刷新时会闪烁
        //当变量的值更新的时候，binding 对象将在下个更新周期中更新。这样就会有一点时间间隔，
        // 如果你像立刻更新，则可以使用 executePendingBindings 函数。
        holder.getBinding()?.executePendingBindings()
        onBind?.invoke(holder.getBinding() as BD, item, position)
    }

    override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): Holder {
        return Holder(inflater.inflate(layoutId, parent, false))
    }


    companion object {
        class Holder(view: View) : RecyclerView.ViewHolder(view) {
            private val b: ViewDataBinding? by lazy {
                DataBindingUtil.bind<ViewDataBinding>(itemView)
            }

            fun getBinding(): ViewDataBinding? {
                return b
            }
        }
    }
}